
#import "MainView.h"

int W=320;
int H=480;

@implementation MainView

- (void) drawRect: (CGRect) rect {    
    
    W = rect.size.width; 
    H = rect.size.height;
    
    @try {
        
        UIImage *carBlueImage = [UIImage imageNamed: @"car_blue.png"];     
        [carBlueImage drawAtPoint: CGPointMake(140, 140)];
        
        UIImage *carRedImage = [UIImage imageNamed: @"car_red.png"];
        UIImage *carGreenImage = [UIImage imageNamed: @"car_green.png"];
        for (int i=0; i<10; i++) {            
            int x, y;
            x = [self getRndBetween: 0 and: W];
            y = [self getRndBetween: 0 and: H];  
            [carBlueImage drawAtPoint: CGPointMake(x, y)];
            x = [self getRndBetween: 0 and: W];
            y = [self getRndBetween: 0 and: H];  
            [carRedImage drawAtPoint: CGPointMake(x, y)];
            x = [self getRndBetween: 0 and: W];
            y = [self getRndBetween: 0 and: H];  
            [carGreenImage drawAtPoint: CGPointMake(x, y)];
        }    
        
        int picW = carBlueImage.size.width; 
        int picH = carBlueImage.size.height;
        NSLog(@"Size of pic: %ix%i", picW, picH);
        
        [carBlueImage drawInRect: CGRectMake(120, 250, picW*2, picH*2)];
        
        [carBlueImage drawAtPoint: CGPointMake(40, 140) 
                        blendMode: kCGBlendModeNormal 
                            alpha: 0.4];
        [carBlueImage drawAtPoint: CGPointMake(25, 125) 
                        blendMode: kCGBlendModeNormal 
                            alpha: 0.4];  
        
        for (int i=0; i<20; i++) {
            [self rotateImage: @"car_green.png"
                            x: [self getRndBetween: 0 and: W]
                            y: [self getRndBetween: 0 and: W]
                        angle: [self getRndBetween: 0 and: 360]];
        }    
        
    } 
	@catch (id theException) {
		NSLog(@"ERROR: Pic(s) not found.");
	} 
}

- (void) rotateImage: (NSString*) picName 
                   x: (int) x 
                   y: (int) y 
               angle: (int) a {
	
    UIImage *pic = [UIImage imageNamed: picName];

	if (pic) {		
		int w = pic.size.width; 
		int h = pic.size.height;
		
		CGContextRef ctx = UIGraphicsGetCurrentContext(); 
		CGContextSaveGState(ctx); 	
		
		CGContextTranslateCTM(ctx, x+w/2, y+h/2);		
		
		CGContextRotateCTM(ctx, [self getRad: a]); 
        
		[pic drawAtPoint: CGPointMake(0-w/2, 0-h/2)];

		CGContextRestoreGState(ctx); 
	} 
} 

- (float) getRad: (float) grad {
	float rad = (M_PI / 180) * grad;
	return rad;
}

- (float) getGrad: (float) rad {
	float grad = (180 / M_PI) * rad;
	return grad;
}

- (int) getRndBetween: (int) bottom and: (int) top {		
	int rnd = bottom + (arc4random() % (top+1-bottom)); 
	return rnd;
}  

@end
